"""
AI Agent Pro - 核心配置模块
"""

import os
from functools import lru_cache
from typing import List, Optional, Any
from pydantic import BaseSettings, Field, validator


class Settings(BaseSettings):
    """应用设置配置类"""
    
    # ====== 基础应用配置 ======
    app_name: str = Field("AI Agent Pro", env="APP_NAME")
    app_version: str = Field("1.0.0", env="APP_VERSION")
    environment: str = Field("development", env="ENVIRONMENT")
    debug: bool = Field(True, env="DEBUG")
    log_level: str = Field("INFO", env="LOG_LEVEL")
    
    # ====== 网络配置 ======
    backend_port: int = Field(8000, env="BACKEND_PORT")
    frontend_port: int = Field(3000, env="FRONTEND_PORT")
    cors_origins: List[str] = Field(
        ["http://localhost:3000", "http://127.0.0.1:3000"],
        env="CORS_ORIGINS"
    )
    
    # ====== 安全配置 ======
    secret_key: str = Field(..., env="SECRET_KEY")
    algorithm: str = Field("HS256", env="ALGORITHM")
    access_token_expire_minutes: int = Field(1440, env="ACCESS_TOKEN_EXPIRE_MINUTES")
    rate_limit_per_minute: int = Field(100, env="RATE_LIMIT_PER_MINUTE")
    
    # ====== 数据库配置 ======
    database_url: str = Field(..., env="DATABASE_URL")
    redis_url: str = Field("redis://localhost:6379/0", env="REDIS_URL")
    qdrant_url: str = Field("http://localhost:6333", env="QDRANT_URL")
    qdrant_api_key: Optional[str] = Field(None, env="QDRANT_API_KEY")
    
    # ====== AI 模型配置 ======
    openai_api_key: Optional[str] = Field(None, env="OPENAI_API_KEY")
    anthropic_api_key: Optional[str] = Field(None, env="ANTHROPIC_API_KEY")
    google_ai_api_key: Optional[str] = Field(None, env="GOOGLE_AI_API_KEY")
    
    # Azure OpenAI 配置
    azure_openai_api_key: Optional[str] = Field(None, env="AZURE_OPENAI_API_KEY")
    azure_openai_endpoint: Optional[str] = Field(None, env="AZURE_OPENAI_ENDPOINT")
    azure_openai_api_version: str = Field("2023-12-01-preview", env="AZURE_OPENAI_API_VERSION")
    
    # ====== 文件存储配置 ======
    local_storage_path: str = Field("./storage", env="LOCAL_STORAGE_PATH")
    max_file_size_mb: int = Field(100, env="MAX_FILE_SIZE_MB")
    allowed_file_types: List[str] = Field(
        [".txt", ".pdf", ".doc", ".docx", ".py", ".js", ".html", ".css", ".json", ".xml"],
        env="ALLOWED_FILE_TYPES"
    )
    
    # AWS S3 配置
    aws_access_key_id: Optional[str] = Field(None, env="AWS_ACCESS_KEY_ID")
    aws_secret_access_key: Optional[str] = Field(None, env="AWS_SECRET_ACCESS_KEY")
    aws_s3_bucket: Optional[str] = Field(None, env="AWS_S3_BUCKET")
    aws_region: str = Field("us-east-1", env="AWS_REGION")
    
    # ====== SMTP 邮件配置 ======
    smtp_host: Optional[str] = Field(None, env="SMTP_HOST")
    smtp_port: int = Field(587, env="SMTP_PORT")
    smtp_username: Optional[str] = Field(None, env="SMTP_USERNAME")
    smtp_password: Optional[str] = Field(None, env="SMTP_PASSWORD")
    smtp_use_tls: bool = Field(True, env="SMTP_USE_TLS")
    
    # ====== 监控配置 ======
    sentry_dsn: Optional[str] = Field(None, env="SENTRY_DSN")
    ga_tracking_id: Optional[str] = Field(None, env="GA_TRACKING_ID")
    prometheus_enabled: bool = Field(True, env="PROMETHEUS_ENABLED")
    
    # ====== 智能体特定配置 ======
    default_agent_model: str = Field("gpt-4", env="DEFAULT_AGENT_MODEL")
    max_conversation_history: int = Field(50, env="MAX_CONVERSATION_HISTORY")
    tool_execution_timeout: int = Field(300, env="TOOL_EXECUTION_TIMEOUT")
    memory_retention_days: int = Field(30, env="MEMORY_RETENTION_DAYS")
    semantic_search_threshold: float = Field(0.8, env="SEMANTIC_SEARCH_THRESHOLD")
    
    # ====== WebSocket 配置 ======
    ws_max_connections: int = Field(100, env="WS_MAX_CONNECTIONS")
    
    # ====== 开发配置 ======
    auto_reload: bool = Field(True, env="AUTO_RELOAD")
    test_database_url: Optional[str] = Field(None, env="TEST_DATABASE_URL")
    mock_ai_apis: bool = Field(False, env="MOCK_AI_APIS")
    
    # ====== 第三方服务集成 ======
    github_token: Optional[str] = Field(None, env="GITHUB_TOKEN")
    slack_bot_token: Optional[str] = Field(None, env="SLACK_BOT_TOKEN")
    slack_signing_secret: Optional[str] = Field(None, env="SLACK_SIGNING_SECRET")
    discord_bot_token: Optional[str] = Field(None, env="DISCORD_BOT_TOKEN")
    telegram_bot_token: Optional[str] = Field(None, env="TELEGRAM_BOT_TOKEN")
    
    # ====== 搜索服务 ======
    google_search_api_key: Optional[str] = Field(None, env="GOOGLE_SEARCH_API_KEY")
    google_search_engine_id: Optional[str] = Field(None, env="GOOGLE_SEARCH_ENGINE_ID")
    bing_search_api_key: Optional[str] = Field(None, env="BING_SEARCH_API_KEY")
    
    # ====== 部署配置 ======
    docker_registry: Optional[str] = Field(None, env="DOCKER_REGISTRY")
    docker_tag: str = Field("latest", env="DOCKER_TAG")
    k8s_namespace: str = Field("ai-agent", env="K8S_NAMESPACE")
    
    @validator("cors_origins", pre=True)
    def parse_cors_origins(cls, v):
        """解析 CORS 来源"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v
    
    @validator("allowed_file_types", pre=True)
    def parse_allowed_file_types(cls, v):
        """解析允许的文件类型"""
        if isinstance(v, str):
            return [file_type.strip() for file_type in v.split(",")]
        return v
    
    @validator("environment")
    def validate_environment(cls, v):
        """验证环境变量"""
        allowed_envs = ["development", "staging", "production"]
        if v not in allowed_envs:
            raise ValueError(f"环境必须是 {allowed_envs} 中的一个")
        return v
    
    @validator("log_level")
    def validate_log_level(cls, v):
        """验证日志级别"""
        allowed_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        if v.upper() not in allowed_levels:
            raise ValueError(f"日志级别必须是 {allowed_levels} 中的一个")
        return v.upper()
    
    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self.environment == "production"
    
    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.environment == "development"
    
    @property
    def database_url_sync(self) -> str:
        """同步数据库 URL (用于 Alembic)"""
        return self.database_url.replace("postgresql+asyncpg://", "postgresql://")
    
    @property
    def max_file_size_bytes(self) -> int:
        """最大文件大小 (字节)"""
        return self.max_file_size_mb * 1024 * 1024
    
    def get_ai_model_config(self) -> dict:
        """获取 AI 模型配置"""
        config = {}
        
        if self.openai_api_key:
            config["openai"] = {
                "api_key": self.openai_api_key,
                "models": ["gpt-4", "gpt-3.5-turbo", "gpt-4-turbo-preview"]
            }
        
        if self.anthropic_api_key:
            config["anthropic"] = {
                "api_key": self.anthropic_api_key,
                "models": ["claude-3-opus", "claude-3-sonnet", "claude-3-haiku"]
            }
        
        if self.google_ai_api_key:
            config["google"] = {
                "api_key": self.google_ai_api_key,
                "models": ["gemini-pro", "gemini-pro-vision"]
            }
        
        if self.azure_openai_api_key and self.azure_openai_endpoint:
            config["azure_openai"] = {
                "api_key": self.azure_openai_api_key,
                "endpoint": self.azure_openai_endpoint,
                "api_version": self.azure_openai_api_version
            }
        
        return config
    
    def get_storage_config(self) -> dict:
        """获取存储配置"""
        config = {
            "local": {
                "path": self.local_storage_path,
                "max_size_mb": self.max_file_size_mb,
                "allowed_types": self.allowed_file_types
            }
        }
        
        if all([self.aws_access_key_id, self.aws_secret_access_key, self.aws_s3_bucket]):
            config["s3"] = {
                "access_key_id": self.aws_access_key_id,
                "secret_access_key": self.aws_secret_access_key,
                "bucket": self.aws_s3_bucket,
                "region": self.aws_region
            }
        
        return config
    
    def get_email_config(self) -> Optional[dict]:
        """获取邮件配置"""
        if not all([self.smtp_host, self.smtp_username, self.smtp_password]):
            return None
        
        return {
            "host": self.smtp_host,
            "port": self.smtp_port,
            "username": self.smtp_username,
            "password": self.smtp_password,
            "use_tls": self.smtp_use_tls
        }
    
    class Config:
        """Pydantic 配置"""
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False


@lru_cache()
def get_settings() -> Settings:
    """获取应用设置 (单例模式)"""
    return Settings()


# 获取设置实例
settings = get_settings()


# 导出常用配置
__all__ = [
    "Settings",
    "get_settings",
    "settings",
]